require 'nokogiri'
require 'open-uri'
require 'nl_gas_stations/parser'
require 'digest'

module NlGasStations

  ROOT_URL = 'http://www.brandstofprijzen.info/'

  class Scraper

    ##
    # Read the data from the source website and parse it.
    # If a cache is configured, a cached value will be returned.
    def self.scrape(params)
      url = ROOT_URL + '?' + params.to_query
      if NlGasStations.configuration.cache.nil?
        html = make_request(url)
        parse(html)
      else

        NlGasStations.configuration.cache.fetch(NlGasStations.configuration.cache_prefix + params.to_query,
                                                expires_in: NlGasStations.configuration.cache_expires_in) do
          html = make_request(url)
          parse(html)
        end
      end
    end

    private

    ##
    # Make a request and return the #Nokogiri::HTML object.
    def self.make_request(url)
      response = open(url)
      Nokogiri::HTML(response)
    end

    ##
    # Parse the #Nokogiri::HTML object with the #Parser cals
    def self.parse(html)
      parser = Parser.new(html)
      parser.parse
    end

  end

end